﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Serialization;

namespace WebApp.Common.Mail
{
    /// <summary>
    /// 邮件发送类
    /// </summary>
    /// <remarks>
    /// 例子：MailSender.SendHtmlMail("abc@163.com", "主题", "邮件内容");
    /// 
    /// </remarks>
    public class MailSender
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MailSender));

        private const string MAIL_XML = "MailServer.xml";
        private const string MASS_MAIL_XML = "MassMailServer.xml";
        private static MailServer smtpserver = null;

        public MailSender()
        {

        }
        
        /// <summary>
        /// 获取邮件服务器设置
        /// </summary>
        private static void LoadMailServer(string mail_xml)
        {
            string configFile = HttpRuntime.AppDomainAppPath + mail_xml;
            using (FileStream fs = new FileStream(configFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {                
				XmlSerializer serializer = new XmlSerializer(typeof(MailServer));
                smtpserver = (MailServer)serializer.Deserialize(fs);
            }
        }

        /// <summary>
        /// 阿里企业邮箱发送邮件
        /// </summary>
        /// <param name="mailto">目标邮箱</param>
        /// <param name="mailsubject">主题</param>
        /// <param name="mailbody">内容</param>
        /// <returns></returns>
        public static string SendHtmlMail2(string mailto, string mailsubject, string mailbody)
        {
            if (smtpserver == null)
            {
                LoadMailServer(MAIL_XML);
            }
            try
            {
                MailMessage mailMsg = new MailMessage();
                mailMsg.To.Add(new MailAddress(mailto));
                mailMsg.From = new MailAddress(smtpserver.Mailfrom, smtpserver.Displayname);
                // 邮件主题
                mailMsg.Subject = mailsubject;
                //回复
                mailMsg.ReplyTo = new MailAddress("UP.China@infineon.com");
                // 邮件正文内容
                //string text = "欢迎使用阿里云邮件推送";
                string html = mailbody; //@"欢迎使用<a href=""https://dm.console.aliyun.com"">邮件推送</a>";
                //mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

                // 添加附件
                //string file = "D:\\1.txt";
                //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                //mailMsg.Attachments.Add(data);
                //邮件推送的SMTP地址和端口
                SmtpClient smtpClient = new SmtpClient(smtpserver.Smtp, smtpserver.Port);
                // 使用SMTP用户名和密码进行验证
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpserver.Username, smtpserver.Password);
                smtpClient.Credentials = credentials;
                smtpClient.Send(mailMsg);

                string content = "邮件发送成功！" + Environment.NewLine;
                content += "From:" + mailMsg.From + Environment.NewLine;
                content += "To:" + mailto + Environment.NewLine;
                content += "Subject:" + mailsubject + Environment.NewLine;
                content += "Body:" + mailbody;

                //Log.Info("_mail.log", content);
                log.Info(content);

                return "";
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.Message;
            }
        }

        /// <summary>
        /// 群发邮件
        /// </summary>
        /// <param name="mailto">目标邮箱</param>
        /// <param name="mailsubject">主题</param>
        /// <param name="mailbody">内容</param>
        /// <returns></returns>
        public static string SendMassMail(string mailto, string mailsubject, string mailbody)
        {
            if (smtpserver == null)
            {
                LoadMailServer(MASS_MAIL_XML);
            }
            try
            {
                MailMessage mailMsg = new MailMessage();
                mailMsg.To.Add(new MailAddress(mailto));
                mailMsg.From = new MailAddress(smtpserver.Mailfrom, smtpserver.Displayname);
                //回复
                mailMsg.ReplyTo = new MailAddress("autoeco@infineon.com");
                // 邮件主题
                mailMsg.Subject = mailsubject;
                // 邮件正文内容
                //string text = "欢迎使用阿里云邮件推送";
                string html = mailbody; //@"欢迎使用<a href=""https://dm.console.aliyun.com"">邮件推送</a>";
                //mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

                // 添加附件
                //string file = "D:\\1.txt";
                //Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                //mailMsg.Attachments.Add(data);
                //邮件推送的SMTP地址和端口
                SmtpClient smtpClient = new SmtpClient(smtpserver.Smtp, smtpserver.Port);
                // 使用SMTP用户名和密码进行验证
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpserver.Username, smtpserver.Password);
                smtpClient.Credentials = credentials;
                smtpClient.Send(mailMsg);

                string content = "邮件发送成功！" + Environment.NewLine;
                content += "From:" + mailMsg.From + Environment.NewLine;
                content += "To:" + mailto + Environment.NewLine;
                content += "Subject:" + mailsubject + Environment.NewLine;
                content += "Body:" + mailbody;

                //Log.Info("_mail.log", content);
                log.Info(content);

                return "";
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.Message;
            }
           
        }
    }
}
